import { useState } from 'react';
import {
  Input,
  Button,
  Table,
  Modal,
  Radio,
  Form,
  Select,
  message,
  Space,
  Upload,
} from 'antd';
import { CheckCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { graphBuilderApi } from 'services';
import { BuildGraphParams, DataSourceTableInfo } from 'types/graph-builder';

import BuildProgressModal from './BuildProgressModal';
import styles from './index.module.css';

const { Option } = Select;

interface GraphAddProps {
  modalVisible: boolean;
  setModalVisible: (visible: boolean) => void;
}

const GraphAdd = ({ modalVisible, setModalVisible }: GraphAddProps) => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(1);
  // 构建方式
  const [buildType, setBuildType] = useState<'structured' | 'unstructured'>(
    'structured'
  );
  // 数据库连接状态
  const [dbConnected, setDbConnected] = useState(false);
  const [graphId, setGraphId] = useState('');
  const [loading, setLoading] = useState(false);
  // 数据源表
  const [dataSourceTables, setDataSourceTables] = useState<
    DataSourceTableInfo[]
  >([]);
  // 选择的数据表名称
  const [selectedTables, setSelectedTables] = useState<DataSourceTableInfo[]>(
    []
  );
  // 构建进度弹窗
  const [buildProgressModalVisible, setBuildProgressModalVisible] =
    useState(false);
  const [nextLoading, setNextLoading] = useState(false);

  // 获取数据源表
  const fetchDataSourceTables = async () => {
    setLoading(true);
    try {
      const res = await graphBuilderApi.getDataSourceTables(+graphId, {
        page_size: 10,
        page: 1,
      });
      if (res.code === 200) {
        setDataSourceTables(res.data.results);
      } else {
        message.error(res.message);
      }
    } catch (error) {
      message.error('获取数据源表失败');
    } finally {
      setLoading(false);
    }
  };

  // 创建图谱
  const handleCreateGraph = async () => {
    setNextLoading(true);
    try {
      const { name } = await form.validateFields();

      const res = await graphBuilderApi.createGraph({
        name,
        graph_type: buildType,
      });

      if (res.code === 200) {
        setGraphId(res.data.id);
        setCurrentStep(2);
      } else {
        message.error('创建图谱失败');
      }
    } catch (error) {
      message.error('创建图谱失败');
    } finally {
      setNextLoading(false);
    }
  };

  // 测试数据库连接
  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields();
      const { dbType, host, port, username, password, database } = values;
      const data = {
        graph_type: buildType,
        data_source: {
          db_type: dbType,
          host,
          port,
          username,
          password,
          db_name: database,
        },
      };

      // 数据库连接测试
      const res = await graphBuilderApi.testDatabaseConnection(data);
      if (res.code === 200) {
        setDbConnected(true);
      } else {
        message.error('连接测试失败');
      }
    } catch (error) {
      message.error('连接测试失败');
    }
  };

  // 保存数据库配置
  const handleSaveDatabaseConfig = async () => {
    setNextLoading(true);
    try {
      const values = await form.validateFields();
      const { dbType, host, port, username, password, database } = values;

      const data = {
        db_type: dbType,
        host,
        port,
        username,
        password,
        db_name: database,
      };
      const res = await graphBuilderApi.saveDatabaseConfig(graphId, data);

      if (res.code === 200) {
        setCurrentStep(3);
        fetchDataSourceTables();
        message.success('数据库配置保存成功');
      } else {
        message.error('数据库配置保存失败');
      }
    } catch (error) {
      message.error('数据库配置保存失败');
    } finally {
      setNextLoading(false);
    }
  };

  // 开始构建
  const handleBuild = async () => {
    setNextLoading(true);

    try {
      // 结构化构建需要传数据库表名，非结构化构建什么都不需要传递
      const data: BuildGraphParams = {};
      if (buildType === 'structured') {
        data.table_name = selectedTables.map((table) => table.table_name) || [];
      }

      const res = await graphBuilderApi.buildGraph(graphId, data);

      if (res.code === 200) {
        // 显示构建进度弹窗
        setBuildProgressModalVisible(true);
      } else {
        message.error('构建失败，请重试');
      }
    } catch (error) {
      message.error('构建失败，请重试');
    } finally {
      setNextLoading(false);
    }
  };

  const handleUploadFile = async () => {
    const value = form.getFieldValue('file');
    const fileList = value?.fileList;

    if (!fileList || fileList.length === 0) {
      message.error('请先选择文件');
      return;
    }

    const formData = new FormData();
    formData.append('file', fileList[0].originFileObj);

    const res = await graphBuilderApi.uploadFile(graphId, formData);

    if (res.code === 200) {
      message.success('文件上传成功');
    } else {
      message.error('文件上传失败');
    }
  };

  // 渲染表单内容
  const renderModalContent = () => {
    if (currentStep === 1) {
      return (
        <>
          <Form.Item
            name="type"
            label="构建方式"
            rules={[{ required: true }]}
            initialValue={buildType}
            valuePropName="checked"
          >
            <Radio.Group
              value={buildType}
              onChange={(e) => setBuildType(e.target.value)}
            >
              <Radio.Button value="structured">结构化</Radio.Button>
              <Radio.Button value="unstructured">非结构化</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="name"
            label="图谱名称"
            rules={[{ required: true }]}
            style={{ marginTop: 16 }}
          >
            <Input placeholder="请输入图谱名称" />
          </Form.Item>
        </>
      );
    }

    if (currentStep === 2 && buildType === 'structured') {
      return (
        <div className={styles.dbConfigForm}>
          <div className={styles.dbConfigTip}>
            <div className={styles.tipIcon}>ℹ️</div>
            <div className={styles.tipContent}>
              请先完成数据库配置并测试连接，连接成功后方可进行下一步操作
            </div>
          </div>

          <Form.Item
            name="dbType"
            label="数据库类型"
            rules={[{ required: true }]}
          >
            <Select placeholder="请选择数据库类型">
              <Option value="mysql">MySQL</Option>
              <Option value="oracle">Oracle</Option>
              <Option value="sqlite3">SQLite3</Option>
              <Option value="postgresql">PostgreSQL</Option>
            </Select>
          </Form.Item>
          <Form.Item name="host" label="主机地址" rules={[{ required: true }]}>
            <Input placeholder="请输入主机地址" />
          </Form.Item>
          <Form.Item name="port" label="端口" rules={[{ required: true }]}>
            <Input placeholder="请输入端口" />
          </Form.Item>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true }]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            name="database"
            label="数据库名"
            rules={[{ required: true }]}
          >
            <Input placeholder="请输入数据库名" />
          </Form.Item>
          <Space style={{ alignItems: 'center', marginBottom: 16 }}>
            <Button
              type="primary"
              onClick={handleTestConnection}
              className={styles.testButton}
            >
              测试连接
            </Button>
            {dbConnected && (
              <div className={styles.connectSuccess}>
                <CheckCircleOutlined /> 连接测试成功
              </div>
            )}
          </Space>
        </div>
      );
    }

    if (currentStep === 3 && buildType === 'structured') {
      return (
        <div>
          <h4>选择需要构建的数据表：</h4>
          <Table
            rowSelection={{
              type: 'checkbox',
              onChange: (selectedRowKeys, selectedRows) => {
                setSelectedTables(selectedRows);
              },
            }}
            columns={[
              { title: '表名', dataIndex: 'table_name' },
              { title: '描述', dataIndex: 'table_comment' },
            ]}
            loading={loading}
            dataSource={dataSourceTables}
            rowKey="table_name"
            size="small"
          />
        </div>
      );
    }

    // 非结构化构建表单
    return (
      <Form.Item name="file">
        <Upload
          beforeUpload={() => false}
          maxCount={1}
          onChange={handleUploadFile}
        >
          <Button icon={<UploadOutlined />}>上传文件</Button>
        </Upload>
      </Form.Item>
    );
  };

  // 获取底部按钮
  const getModalFooterButtons = () => {
    const buttons = [];

    // 返回按钮
    buttons.push(
      <Button
        key="back"
        onClick={() => {
          if (currentStep === 1) {
            setModalVisible(false);
          } else {
            setCurrentStep(currentStep - 1);
          }
        }}
      >
        {currentStep === 1 ? '取消' : '上一步'}
      </Button>
    );

    // 下一步/开始构建按钮
    if (buildType === 'structured') {
      buttons.push(
        <Button
          key="next"
          type="primary"
          loading={nextLoading}
          disabled={currentStep === 2 && !dbConnected}
          onClick={() => {
            if (currentStep === 1) {
              // 第一步创建图谱
              handleCreateGraph();
            } else if (currentStep === 2 && dbConnected) {
              // 数据库连接成功后，保存数据
              handleSaveDatabaseConfig();
            } else if (currentStep === 3) {
              // 第三步开始构建
              handleBuild();
            }
          }}
        >
          {currentStep === 3 ? '开始构建' : '下一步'}
        </Button>
      );
    } else {
      buttons.push(
        <Button
          key="next"
          type="primary"
          onClick={() => {
            if (currentStep === 1) {
              // 第一步创建图谱
              handleCreateGraph();
            } else {
              // 非结构化构建
              handleBuild();
            }
          }}
        >
          {currentStep === 1 ? '下一步' : '开始构建'}
        </Button>
      );
    }

    return buttons;
  };

  return (
    <>
      <Modal
        title={`新建图谱 (${currentStep}/${buildType ? 3 : 2})`}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setCurrentStep(1);
          setDbConnected(false);
          setSelectedTables([]);
          form.resetFields();
        }}
        footer={getModalFooterButtons()}
        style={{ zIndex: 1000 }} // 添加基础层级
        maskClosable={false}
      >
        <Form
          form={form}
          colon={false}
          labelCol={{ span: 5 }}
          style={{ marginTop: 20 }}
        >
          {renderModalContent()}
        </Form>
      </Modal>

      {/* 构建进度弹窗 */}
      <BuildProgressModal
        open={buildProgressModalVisible}
        graphId={graphId}
        onClose={() => {
          setBuildProgressModalVisible(false);
          setModalVisible(false);
          // 关闭弹窗后，重置表单
          form.resetFields();
          setCurrentStep(1);
          setDbConnected(false);
          setSelectedTables([]);
          setGraphId('');
        }}
      />
    </>
  );
};

export default GraphAdd;
